<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="出库单编号" prop="salseCode">
        <el-input
          v-model="queryParams.salseCode"
          placeholder="请输入出库单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售订单编号" prop="soCode">
        <el-input
          v-model="queryParams.soCode"
          placeholder="请输入销售订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择单据状态"
          clearable
        >
          <el-option label="草稿" value="草稿" label-width="40px" />
          <el-option label="已审核" value="已审核" label-width="40px" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['salse:salse:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['salse:salse:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['salse:salse:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="salseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出库单编号" align="center" prop="salseCode">
        <template #default="scope">
          <a @click="handleView(scope.row)">{{ scope.row.salseCode }}</a>
        </template>
      </el-table-column>
      <el-table-column label="出库单名称" align="center" prop="salseName" />
      <!-- <el-table-column label="出货检验单" align="center" prop="oqcCode" /> -->
      <el-table-column label="销售订单编号" align="center" prop="soCode" />
      <el-table-column label="客户编码" align="center" prop="clientCode" />
      <el-table-column label="客户名称" align="center" prop="clientName" />
      <el-table-column label="出库日期" align="center" prop="salseDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.salseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['salse:salse:edit']"  :disabled="scope.row.status === '出库成功'"  
          :title="scope.row.status === '出库成功' ? '已出库单据不可修改' : ''">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['salse:salse:remove']"  :disabled="scope.row.status === '出库成功'"  
          :title="scope.row.status === '出库成功' ? '已出库单据不可修改' : ''">删除</el-button>
          <el-button link type="primary" icon="Check" @click="outSale(scope.row)" v-hasPermi="['salse:salse:execute']">执行出库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改销售出库单对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="salseRef" :model="form" :rules="rules" label-width="100px">
        <!-- 第一行：出库单编号 + 自动生成开关 + 出库单名称 -->
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="出库单编号" prop="salseCode" label-width="100px">
              <el-input 
                v-model="form.salseCode" 
                placeholder="请输入出库单编号" 
                :disabled="autoGenerate" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="自动生成" label-width="80px">
              <el-switch 
                v-model="autoGenerate" 
                active-text="是" 
                inactive-text="否" 
                @change="handleAutoGenerate" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库单名称" prop="salseName" label-width="100px">
              <el-input v-model="form.salseName" placeholder="请输入出库单名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：出货检验单 + 销售订单编号 + 客户编码（带搜索） -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="销售订单编号" prop="soCode">
              <el-input v-model="form.soCode" placeholder="请输入销售订单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户编码" prop="clientCode">
              <el-input 
                v-model="form.clientCode" 
                placeholder="请输入客户编码" 
                style="width: 180px" />
              <el-button :icon="Search" @click="dialogClientVisible = true" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：客户名称 + 出库日期 + 单据状态 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" placeholder="请输入客户名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库日期" prop="salseDate">
              <el-date-picker 
                v-model="form.salseDate" 
                type="date" 
                placeholder="请选择出库日期" 
                value-format="YYYY-MM-DD" 
                clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择单据状态">
                <el-option label="草稿" value="草稿" />
                <el-option label="已审核" value="已审核" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：备注 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 物料信息子区域（示例表格，实际需替换为子组件） -->
      <div style="margin-top: 20px; border-top: 1px solid #eee; padding-top: 20px;" v-if="form.salseId">

        <h3 style="text-align: center; margin-bottom: 10px;">物料信息</h3>
        <SaleLine :current-salseId="form.salseId"></SaleLine>
        <!-- <el-table :data="materialList" border style="width: 100%">
          <el-table-column label="产品编码" prop="productCode" />
          <el-table-column label="产品名称" prop="productName" />
          <el-table-column label="规格型号" prop="specification" />
          <el-table-column label="单位" prop="unit" />
          <el-table-column label="出库数量" prop="outQuantity" />
          <el-table-column label="批次号" prop="batchCode" />
          <el-table-column label="仓库名称" prop="warehouseName" />
          <el-table-column label="库区名称" prop="locationName" />
        </el-table>
        <el-row :gutter="10" class="mt-3">
          <el-button type="primary" plain icon="Plus" @click="addMaterial" v-hasPermi="['salse:material:add']">新增物料</el-button>
          <el-button type="success" plain icon="Edit" :disabled="materialSingle" @click="editMaterial" v-hasPermi="['salse:material:edit']">修改物料</el-button>
          <el-button type="danger" plain icon="Delete" :disabled="materialMultiple" @click="delMaterial" v-hasPermi="['salse:material:remove']">删除物料</el-button>
        </el-row> -->
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>

      <!-- 出货检验单选择弹窗（示例） -->
      <el-dialog v-model="dialogOqcVisible" title="选择出货检验单" width="600px" append-to-body>
        <el-table :data="oqcList" @selection-change="handleOqcSelection">
          <el-table-column type="selection" width="55" />
          <el-table-column label="检验单编号" prop="oqcCode" />
          <el-table-column label="检验状态" prop="status" />
        </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="confirmOqc">确定选择</el-button>
            <el-button @click="dialogOqcVisible = false">取消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 客户选择弹窗（示例） -->
      <el-dialog v-model="dialogClientVisible" title="选择客户" width="600px" append-to-body>
        <el-table :data="clientList" @selection-change="handleClientSelection">
          <el-table-column type="selection" width="55" />
          <el-table-column label="客户编码" prop="clientCode" />
          <el-table-column label="客户名称" prop="clientName" />
        </el-table>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="confirmClient">确定选择</el-button>
            <el-button @click="dialogClientVisible = false">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup name="Salse">
import { listSalse, getSalse, delSalse, addSalse, updateSalse,outSaleline,updateSalseStatus } from "@/api/salse/salse"; // 替换为实际接口
import { Search, Edit, Delete, Check } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import Pagination from '@/components/Pagination'; // 分页组件
import RightToolbar from '@/components/RightToolbar'; // 右侧工具栏
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';
// import { parseTime } from '@/utils/parse-time'; // 时间格式化工具
import { download } from '@/utils/request'; // 下载工具
import SaleLine from '@/views/saleline/saleline/index.vue'
import { listClient } from '@/api/client/client.js'
const { proxy } = getCurrentInstance();

// 基础数据与状态
const salseList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 自动生成编号逻辑
const autoGenerate = ref(true);
const generateSalseCode = () => {
  const now = dayjs();
  return 'PS' + now.format('YYYYMMDDHHmmss'); // 编号规则：PS+时间戳
};
const handleAutoGenerate = (isAuto) => {
  form.value.salseCode = isAuto ? generateSalseCode() : '';
};

// 弹窗控制
const dialogOqcVisible = ref(false);
const dialogClientVisible = ref(false);


// 物料子表数据与操作
const materialList = ref([]);
const materialIds = ref([]);
const materialSingle = ref(true);
const materialMultiple = ref(true);
const addMaterial = () => { 
  // 实际需补充“新增物料”逻辑（如打开物料弹窗）
  proxy.$modal.msgInfo("新增物料功能待实现");
};
const editMaterial = () => { 
  // 实际需补充“修改物料”逻辑
  proxy.$modal.msgInfo("修改物料功能待实现");
};
const delMaterial = () => { 
  // 实际需补充“删除物料”逻辑
  proxy.$modal.msgInfo("删除物料功能待实现");
};

// 出货检验单选择（示例数据，实际需对接接口）
const oqcList = ref([
  { oqcId: 1, oqcCode: 'OQC20220901004', status: '已完成' },
]);
const selectedOqc = ref(null);
const handleOqcSelection = (selection) => {
  selectedOqc.value = selection.length > 0 ? selection[0] : null;
};
const confirmOqc = () => {
  if (selectedOqc.value) {
    form.value.oqcCode = selectedOqc.value.oqcCode;
    dialogOqcVisible.value = false;
  } else {
    proxy.$modal.msgWarning('请选择出货检验单');
  }
};

// 客户选择（示例数据，实际需对接接口）
const clientList = ref([
]);
const selectedClient = ref(null);
const handleClientSelection = (selection) => {
  selectedClient.value = selection.length > 0 ? selection[0] : null;
};
const confirmClient = () => {
  if (selectedClient.value) {
    form.value.clientCode = selectedClient.value.clientCode;
    form.value.clientName = selectedClient.value.clientName;
    dialogClientVisible.value = false;
  } else {
    proxy.$modal.msgWarning('请选择客户');
  }
};

// 表单与查询参数
const data = reactive({
  form: {
    salseId: null,
    salseCode: generateSalseCode(), // 初始自动生成编号
    salseName: null,
    oqcId: null,
    oqcCode: null,
    soCode: null,
    clientId: null,
    clientCode: null,
    clientName: null,
    salseDate: dayjs().format('YYYY-MM-DD'), // 初始为当天
    status: '草稿', // 初始为草稿状态
    remark: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    salseCode: null,
    soCode: null,
    clientName: null,
    salseDate: null,
    status: null,
  },
  rules: {
    salseCode: [{ required: true, message: "出库单编号不能为空", trigger: "blur" }],
    salseName: [{ required: true, message: "出库单名称不能为空", trigger: "blur" }],
    clientCode: [{ required: true, message: "客户编码不能为空", trigger: "blur" }],
    salseDate: [{ required: true, message: "出库日期不能为空", trigger: "change" }],
  }
});
const { queryParams, form, rules } = toRefs(data);

// 查询销售出库单列表
function getList() {
  loading.value = true;
  listSalse(queryParams.value).then(response => {
    salseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    listClient().then(response =>{
      clientList.value = response.rows
    })
  });
}
//得到kehuxinxi
function getClient(){
  
}
// 取消对话框
function cancel() {
  open.value = false;
  reset();
}


// 表单重置
function reset() {
  form.value = {
    salseId: null,
    salseCode: autoGenerate.value ? generateSalseCode() : '',
    salseName: null,
    oqcId: null,
    oqcCode: null,
    soCode: null,
    clientId: null,
    clientCode: null,
    clientName: null,
    salseDate: dayjs().format('YYYY-MM-DD'),
    status: '草稿',
    remark: null,
  };
  materialList.value = []; // 重置物料列表
  materialIds.value = [];
  proxy.resetForm("salseRef"); // 重置表单校验
}

// 搜索按钮
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置搜索表单
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 表格多选框选中事件
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.salseId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 新增销售出库单
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加销售出库单";
  autoGenerate.value = true; // 新增时默认自动生成编号
  form.value.salseCode = generateSalseCode();
}

// 修改销售出库单
function handleUpdate(row) {
  reset();
  const _salseId = row.salseId || ids.value;
  getSalse(_salseId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改销售出库单";
    autoGenerate.value = false; // 编辑时关闭自动生成（编号已存在）
    // 实际需调用“根据出库单ID查物料”的接口，示例省略
    // getMaterialList(_salseId).then(res => {
    //   materialList.value = res.data;
    // });
  });
}

// 提交表单（新增/修改）
function submitForm() {
  proxy.$refs["salseRef"].validate(valid => {
    if (valid) {
      const request = form.value.salseId ? updateSalse : addSalse;
      request(form.value).then(() => {
        proxy.$modal.msgSuccess(form.value.salseId ? "修改成功" : "新增成功");
        open.value = false;
        getList(); // 刷新列表
      });
    }
  });
}

// 删除销售出库单
function handleDelete(row) {
  const _salseIds = row.salseId || ids.value;
  proxy.$modal.confirm(`是否确认删除销售出库单编号为"${_salseIds}"的数据项？`).then(() => {
    return delSalse(_salseIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
// 出库
function outSale(row) {
  console.log("执行了出库");
  const _salseIds = row.salseId || ids.value;
  
  proxy.$modal.confirm(`是否确认执行出库单【${row.salseCode}】的出库操作？`).then(() => {
    // 状态校验
    if (row.status === '出库成功') {
      proxy.$modal.msgWarning('单据已出库,无法继续出库');
      return Promise.reject();
    } else if (row.status === '草稿') {
      proxy.$modal.msgWarning('单据未审批，不可执行出库操作，请先审批');
      return Promise.reject();
    } else {
      // 调用出库接口
      return outSaleline(_salseIds);
    }
  }).then((response) => {
    console.log("出库接口完整返回数据：", response);
    // 关键：直接使用row中的salseId（无需从response获取）
    return changeStatus(row.salseId); // 此处修改为row.salseId
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("出库成功，状态已更新为“已出库”");
  }).catch((error) => {
    if (error) {
      proxy.$modal.msgError(error.message || '出库操作失败');
    }
  });
}
// 出库成功后修改单据状态为“已出库”
function changeStatus(salseId) {
  // 调用状态更新接口，传入单据ID和目标状态“已出库”
  return updateSalseStatus(salseId, '出库成功')
    .then(response => {
      return response; // 将结果传递给下一个then
    })
    .catch(error => {
      // 状态更新失败的处理
      console.error(`单据${salseId}状态更新失败`, error);
      throw new Error('状态更新失败，请重试'); // 抛出错误，触发外层catch
    });
}

// 导出销售出库单
function handleExport() {
  proxy.download('salse/salse/export', {
    ...queryParams.value
  }, `salse_${new Date().getTime()}.xlsx`);
}

// 初始化加载列表
getList();
</script>

<style scoped>
.app-container {
  padding: 16px;
}
.mb8 {
  margin-bottom: 8px;
}
.mt-3 {
  margin-top: 12px;
}
</style>